package devcamp.teama.yahooooooo.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import devcamp.teama.yahooooooo.dao.YahoooooooDao;
import devcamp.teama.yahooooooo.dto.LocationDto;
import devcamp.teama.yahooooooo.json.UserJson;
import devcamp.teama.yahooooooo.json.UserListJson;
import devcamp.teama.yahooooooo.util.ParameterUtils;
import devcamp.teama.yahooooooo.util.YahoooooooUtils;

@SuppressWarnings("serial")
public class UserListServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        getUserList(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        getUserList(req, resp);
    }

    void getUserList(HttpServletRequest req, HttpServletResponse resp) {
        UserListJson json = new UserListJson();
        Float latitude = null;
        Float longitude = null;
        String strLatitude = req.getParameter(ParameterUtils.LATITUDE);
        String strLongitude = req.getParameter(ParameterUtils.LONGITUDE);
        // 数値変換
        try {
            latitude = YahoooooooUtils.String2Float(strLatitude);
            longitude = YahoooooooUtils.String2Float(strLongitude);
        } catch (NumberFormatException e) {
            //FIXME:エラーログの出力。エラーログにその時の文字列を入れておく
            json.registration = false;
            printJson(resp, YahoooooooUtils.Object2Json(json));
            return;
        }
        // データ取得
        YahoooooooDao dao = new YahoooooooDao();
        List<LocationDto> list = dao.findUserById(latitude, longitude);
        // 0件ならfalseを返す
        if (list == null || list.size() == 0) {
            json.registration = false;
            printJson(resp, YahoooooooUtils.Object2Json(json));
            return;
        }
        // データ作成
        List<UserJson> jsonList = new ArrayList<UserJson>();
        for (LocationDto tmp : list) {
            UserJson user = new UserJson();
            user.latitude = tmp.getLatitude();
            user.longitude = tmp.getLongitude();
            user.location = tmp.getLocation();
            user.twitterId = tmp.getTwitterId();
            user.username = tmp.getUserName();
            jsonList.add(user);
        }

        json.registration = true;
        json.user = jsonList;
        printJson(resp, YahoooooooUtils.Object2Json(json));
    }

    void printJson(HttpServletResponse resp, String outputJson) {
        resp.setContentType("text/plain");
        try {
            resp.getWriter().print(outputJson);
        } catch (IOException e) {
            e.printStackTrace();
            // FIXME:ログの出力
        }
    }
}
